package spsu.cs6903.assignment3;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class TicTacToeActivity extends Activity {
	
	 TextView messageView;	 
	 String message;
	 Button srButton;
	 boolean player1 = true;
	 int moves = 0;
	 boolean gameOver = false;	 
	 boolean gameStarted = false;
	 GameBoard gb; 
	 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        messageView=(TextView) findViewById(R.id.message);
        srButton = (Button) findViewById(R.id.srButton);
    }
    
   
// @parm string message passed to the messageView 
    
    private void updateMessageView(){
        messageView.setText(message);
    }
    

    public void onStartClick(View v){
    	
    	if(!gameStarted)
    	{
    		message = "Player 1 make your move!";
	    	gameStarted = true;
	    	gb = new GameBoard();
	    	srButton.setText("Reset");		    	
    	}
	    else
	    {
	    	gameStarted = false;
	    	finish();
	    	startActivity(new Intent(TicTacToeActivity.this, TicTacToeActivity.class));	    	
	    }
    	updateMessageView();  
    }
       
    public void onMoveClick(View v){
    	if(gameStarted)
    	{
       	   	v.setClickable(false);
	    	
	    	if((player1) && (!gameOver))
	    	{
	    		v.setBackgroundResource(R.drawable.x);
	    		for(int i=0; i <9;i++)
	    		{
	    			if(v.getId() == gb.board[i].getButton())
	    			{
	    				 gb.board[i].setValue(1);
	    			}
	    		}
	    		
	    		gb.checkWinner(1);
	    		message = "Player 2 make your move!";
	    		player1 = false;        	        	
	    	}
	    	else if (!gameOver) 
	    	{
	    		v.setBackgroundResource(R.drawable.o);
	    		for(int i=0; i <9;i++)
	    		{
	    			if(v.getId() == gb.board[i].getButton())
	    			{
	    				 gb.board[i].setValue(2);
	    			}
	    		}
	    	  gb.checkWinner(2);
	    		message = "Player 1 make your move!";
	    		player1 = true;        	   
	    	}
	    	moves++;
	    	checkGameOver();
       }
    	else
    	{
    		message = "Please push Start to play!";
    	}
    	updateMessageView();
    }  
    
    public void checkGameOver(){
    	if ((moves == 9) && gb.getWinner() == 0)
    	{
    		gameOver = true;
    		message = "Game is a Draw!!!";    		
    	}
    	else if (gb.getWinner() != 0)
    	{
    		gameOver = true;
    		message = "Player " + gb.getWinner() + " wins!!!";    		
    	}
    	else
    		gameOver = false;
    }
    	      
}